<template>
  <div class="createPost-container">
    <!-- 通过infoloading控制页面每次getData时重新生成form，解决富文本编辑器无法编辑的bug -->
    <div v-if="!infoLoading">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              问题单号：<b style="padding-right:20px">{{ postForm.orderNo }}</b>
              报修人：<b style="padding-right:20px">{{ postForm.submitUserName }}</b>
              房间：<b style="padding-right:20px">{{ postForm.roomNo }}</b>
              电话：<b style="padding-right:20px">{{ postForm.telephone }}</b>
              故障类型：<b style="padding-right:20px">{{ postForm.faultText }}</b>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              响应级别：<b style="padding-right:20px">{{ postForm.priorityText }}</b>
              创建时间：<b style="padding-right:20px">{{ postForm.createDate }}</b>
              限时完成时间：<b style="padding-right:20px">{{ postForm.limitDate }}</b>
              流程名称：<b style="padding-right:20px">{{ postForm.flowType===1?'需要审批':'不需要审批' }}</b>
            </div>
          </el-col>
        </el-row>
        <h2>问题描述</h2>
        <div style="margin: 20px;font-size:16px;line-height:200%" v-html="postForm.description" />

        <!--处理结果信息-->
        <template v-if="postForm.statusClassCode==='0205'||postForm.statusClassCode==='0206'">
          <hr id="hr2" style="margin:30px 0;">
          <el-row>
            <el-col :span="24">
              <div class="postInfo-container">
                运维人：<b style="padding-right:20px">{{ postForm.processingUserName }}</b>
                处理完成时间：<b style="padding-right:20px">{{ postForm.completedDate }}</b>
              </div>
            </el-col>
          </el-row>
          <h2>问题分析</h2>
          <div style="margin: 20px;font-size:16px;line-height:200%" v-html="postForm.analysis" />
          <h2>解决方案</h2>
          <div style="margin: 20px;font-size:16px;line-height:200%" v-html="postForm.solving" />
        </template>
        <!--处理结果信息结束-->
        <!--评价结果信息-->
        <template v-if="postForm.closeSatisfy||postForm.submitSatisfy">
          <hr id="hr2" style="margin:30px 0;">
          <el-row>
            <el-col :span="24">
              <div class="postInfo-container">
                <template v-if="postForm.submitSatisfy">创建人（{{ postForm.submitUserName }}）评价：<b style="padding-right:20px">{{ satisfyText(postForm.submitSatisfy) }}</b></template>
                <template v-if="postForm.closeSatisfy">结束人（{{ postForm.closeUserName }}）评价：<b style="padding-right:20px">{{ satisfyText(postForm.closeSatisfy) }}</b></template>
              </div>
            </el-col>
          </el-row>
        </template>
        <!--评价结果信息结束-->
      </div>
      <h2>转知识库</h2>
      <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="postForm.title" style="width:300px" />
        </el-form-item>
        <el-form-item label="类别" prop="faultClassCode">{{ postForm.faultText }}
        </el-form-item>
        <el-form-item label="描述" prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>
        <el-form-item style="margin-bottom: 30px;">
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>

import Tinymce from '@/components/Tinymce'
const defaultForm = {
  title: '',
  content: ''
}
export default {
  name: 'ArticleDetail',
  components: { Tinymce },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      roleName: '',
      deptName: '',
      realName: '',
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      deptOption: [],
      userOption: [],
      processUserOption: [],
      priorityOption: [],
      classCodeOption: [],
      flowTypeOption: [],
      rules: {
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      tempRoute: {},
      processListLoading: false,
      processList: [],
      processNow: {}
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('timestamp:' + val)
        console.log('infoid:' + this.infoid)
        this.getData(this.infoid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getOptions()
    const day = new Date()
    day.setTime(day.getTime())
    console.log(JSON.parse(localStorage.getItem('user')))
    this.roleName = JSON.parse(localStorage.getItem('user')).roleName
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    satisfyText(val) {
      if (val) {
        switch (val) {
          case '0301':
            return '满意'
          case '0302':
            return '一般'
          case '0303':
            return '不满意'
        }
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData(id) {
      this.getProcessUsers()
      this.infoLoading = true
      this.processListLoading = true
      if (id) {
        this.$http
          .get('/api/workOrder/processDetails?&workOrderId=' + id)
          .then(response => {
            this.infoLoading = false
            this.processListLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result.workOrder
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
            this.processListLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
          if (this.roleName === '法院用户') {
            this.postForm.submitDeptId = JSON.parse(localStorage.getItem('user')).deptId
            this.postForm.submitUserId = JSON.parse(localStorage.getItem('user')).id
            this.deptName = JSON.parse(localStorage.getItem('user')).deptName
            this.realName = JSON.parse(localStorage.getItem('user')).realName
          }
        })
      }
    },
    getOptions() {
      let code = '01'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.priorityOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      code = '04'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.classCodeOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      this.$http
        .get('/api/sysDept/currUnitDepts')
        .then(response => {
          if (response.data.success === true) {
            this.deptOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
      code = '05'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          if (response.data.success === true) {
            this.flowTypeOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getUsers() {
      this.$http
        .get('/api/sysUser/deptUsers?deptId=' + this.postForm.submitDeptId)
        .then(response => {
          if (response.data.success === true) {
            this.userOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getProcessUsers() {
      this.$http
        .get('/api/sysUser/getProcessAuthUsers')
        .then(response => {
          if (response.data.success === true) {
            this.processUserOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    setUser() {
      this.postForm.roomNo = this.userOption.find(item => item.id === this.postForm.submitUserId).roomNo
      this.postForm.telephone = this.userOption.find(item => item.id === this.postForm.submitUserId).phone
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const para = {
            title: this.postForm.title,
            content: this.postForm.content,
            orderId: this.infoid
          }
          this.loading = true
          this.$http
            .post('/api/workOrder/saveToKnowledge', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.$emit('dialogHide')
                this.postForm = Object.assign({}, defaultForm)
                this.loading = false
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
